package com.charity.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.charity.domain.News;
import com.charity.service.INewsService;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/news")
public class NewsController {

    @Resource
    private INewsService newsService;

    @PostMapping("/create")
    public ResponseEntity<Map<String, Object>> createNews(@RequestBody News news) {
        Map<String, Object> response = new HashMap<>();
        if (newsService.createNews(news)) {
            response.put("code", 200);
            response.put("message", "发布成功");
        } else {
            response.put("code", 400);
            response.put("message", "发布失败");
        }
        return ResponseEntity.ok(response);
    }

    @PutMapping("/update")
    public ResponseEntity<Map<String, Object>> updateNews(@RequestBody News news) {
        Map<String, Object> response = new HashMap<>();
        if (newsService.updateNews(news)) {
            response.put("code", 200);
            response.put("message", "更新成功");
        } else {
            response.put("code", 400);
            response.put("message", "更新失败");
        }
        return ResponseEntity.ok(response);
    }

    @DeleteMapping("/delete/{newsId}")
    public ResponseEntity<Map<String, Object>> deleteNews(@PathVariable Long newsId) {
        Map<String, Object> response = new HashMap<>();
        if (newsService.deleteNews(newsId)) {
            response.put("code", 200);
            response.put("message", "删除成功");
        } else {
            response.put("code", 400);
            response.put("message", "删除失败");
        }
        return ResponseEntity.ok(response);
    }

    @GetMapping("/detail/{newsId}")
    public ResponseEntity<Map<String, Object>> getNewsDetail(@PathVariable Long newsId) {
        Map<String, Object> response = new HashMap<>();
        News news = newsService.getNewsById(newsId);
        if (news != null) {
            response.put("code", 200);
            response.put("message", "获取成功");
            response.put("data", news);
        } else {
            response.put("code", 404);
            response.put("message", "新闻不存在");
        }
        return ResponseEntity.ok(response);
    }

    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getNewsList(
            @RequestParam(required = false) String category,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        Map<String, Object> response = new HashMap<>();
        Page<News> newsList = newsService.getNewsList(category, pageNum, pageSize);
        response.put("code", 200);
        response.put("message", "获取成功");
        response.put("data", newsList);
        return ResponseEntity.ok(response);
    }
}